using Microsoft.Extensions.Logging;
using Org.Apache.Rocketmq;
using Vin.Extension.RocketMQ.Models;
using Vin.Extension.RocketMQ.Service;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssemblyCategory;

namespace Vin.Extension.RocketMQ.BackgroundService;

public class InitVinConsumerBackgroundService : Microsoft.Extensions.Hosting.BackgroundService
{
    private ILogger Logger => VinApp.GetLogger(this.GetType());

    private List<VinConsumer> _vinConsumers = new();

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            var types = AssemblyTool.GetTypes<VinConsumer>();
            foreach (var type in types)
            {
                if (type.IsAbstract || type.BaseType != typeof(VinConsumer)) continue;
                var vinConsumer = (Activator.CreateInstance(type) as VinConsumer)!;
                await vinConsumer.Init();
                _vinConsumers.Add(vinConsumer);
            }
        }
        catch (Exception e)
        {
            Logger.LogError(e, "消费者启动失败");
        }

        await Task.Delay(Timeout.Infinite, stoppingToken);
        
        foreach (var vinConsumer in _vinConsumers)
        {
            vinConsumer.Dispose();
        }
    }
}